package icu.xuyijie.springbootlearning1.chapter4.async;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author 徐一杰
 * @date 2025/03/06 13:53
 * @description 线程池配置
 */
@Configuration
public class ThreadPoolConfig {

    @Bean
    public ThreadPoolTaskExecutor taskExecutor() {
        // 获取电脑线程数量
        // int availableProcessors = Runtime.getRuntime().availableProcessors();

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置线程池名称
        executor.setThreadNamePrefix("徐一杰-");

        // 设置线程池核心线程数
        executor.setCorePoolSize(4);
        // 设置线程池最大线程数，如果等待队列满了，会开辟新线程，直到达到最大线程数
        executor.setMaxPoolSize(8);
        // 等待队列长度，如果提交的任务数量大于核心线程数，会添加到队列等待
        executor.setQueueCapacity(4);
        // 配置拒绝策略，默认是 AbortPolicy，直接拒绝并报错
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        executor.initialize();
        return executor;
    }

    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();

        // 设置线程池名称
        scheduler.setThreadNamePrefix("定时任务-");

        // 设置线程池线程数
        scheduler.setPoolSize(4);
        // 配置拒绝策略，默认是 AbortPolicy，直接拒绝并报错
        scheduler.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        scheduler.initialize();
        return scheduler;
    }

}
